/////////////////////////////////////////////
// ObjectARX defined commands

#include "StdAfx.h"
#include "StdArx.h"


// This is command 'LWPOLY'
void lwpoly()
{
	AcDbDatabase *pCurDb;
	AcDbBlockTable *pBlkTable;
	AcDbBlockTableRecord *pBlkTableRecord;
	AcDbPolyline *pPolyEnt;

	AcDbObjectId polyId;

	AcGePoint2d pkPt;
	AcGePoint2dArray arPts;
	ads_point pick, lastpt;
	AcGeMatrix3d ucsMat;
	AcGeMatrix2d ucsMat2d;

	int retCode;
	int numPts;

	Adesk::Boolean keepPicking = Adesk::kTrue;
	Adesk::Boolean firstPick = Adesk::kTrue;

	// Polylines are created in terms of the
	// Entity Coordinate System as opposed to
	// the World Coordinate System. If we are
	// using a UCS other than WCS we need to
	// translate back to the ECS.

	acdbUcsMatrix(ucsMat);
	ucsMat2d(0,0) = ucsMat(0,0);
	ucsMat2d(0,1) = ucsMat(0,1);
	ucsMat2d(0,2) = ucsMat(0,3);
	ucsMat2d(1,0) = ucsMat(1,0);
	ucsMat2d(1,1) = ucsMat(1,1);
	ucsMat2d(1,2) = ucsMat(1,3);

	while(keepPicking)
	{
		if(firstPick)
		{
			retCode = acedGetPoint(NULL, "\nPick first point: ", pick);
			firstPick = Adesk::kFalse;
		}
		else
		{			
			acdbPointSet(pick, lastpt);
			retCode = acedGetPoint(pick, "\nPick another point - [ENTER] for no more: ", pick);
			acedGrDraw(lastpt, pick, 1, 0);
		}
		if(retCode != RTNORM)
		{
			keepPicking = Adesk::kFalse;
			break;
		}

		pkPt.x = pick[X];
		pkPt.y = pick[Y];

		// Append the picked point to the AcGePoint2dArray
		arPts.append(pkPt);
	}// while


	// Clear out the grdraw drawn vectors
	acedRedraw(NULL, 1);

	// Check to see if the AcGePoint2dArray is empty
	if(arPts.isEmpty())
	{
		acutPrintf("\nEmpty array.");
		return;
	}

	// Check to see if we have enough points
	// to draw the polyline
	if(arPts.length() < 2)
	{
		acutPrintf("\nArray only contains one point.");
		return;
	}

	numPts = arPts.length();

	pCurDb = acdbHostApplicationServices()->workingDatabase();
	// Get the model space Block Table Record
	pCurDb->getBlockTable(pBlkTable, AcDb::kForRead);
	pBlkTable->getAt(ACDB_MODEL_SPACE, pBlkTableRecord, AcDb::kForWrite);
	pBlkTable->close();

	pPolyEnt = new AcDbPolyline(numPts);

	// Process the AcGePoint2dArray and add verticies to
	// our polyline.
	for(int idx = 0; idx < numPts; idx++)
	{
		pkPt = arPts.at(idx);
		pkPt.transformBy(ucsMat2d);
		pPolyEnt->addVertexAt(idx, pkPt);
	}

	// Add the AcDbPolyline entity to the Block
	// Table Record
	pBlkTableRecord->appendAcDbEntity(polyId, pPolyEnt);

	pBlkTableRecord->close();
	pPolyEnt->close();
}

